package com.example.controller;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.example.common.Result;
import com.example.entity.Activity;
import com.example.entity.ActivityJoin;
import com.example.entity.User;
import com.example.exception.CustomException;
import com.example.service.ActivityJoinService;
import com.example.service.ActivityService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/api/activityJoin")
public class ActivityJoinController {
    @Resource
    private ActivityJoinService activityJoinService;
    @Resource
    private HttpServletRequest request;
    @Resource
    private ActivityService activityService;

    public User getUser() {
        User user = (User) request.getSession().getAttribute("user");
        if (user == null) {
            throw new CustomException("-1", "请登录");
        }
        return user;
    }

    @PostMapping
    public Result<?> save(@RequestBody ActivityJoin activityJoin) {
        ActivityJoin one = activityJoinService.getOne(Wrappers.<ActivityJoin>lambdaQuery().eq(ActivityJoin::getActivityId, activityJoin.getActivityId())
                .eq(ActivityJoin::getUserId, activityJoin.getUserId()));
        if (one != null) {
            throw new CustomException("-1", "您已经在该团中");
        }
        Long activityId = activityJoin.getActivityId();
        Activity activity = activityService.getById(activityId);
        List<ActivityJoin> list = activityJoinService.list(Wrappers.<ActivityJoin>lambdaQuery().eq(ActivityJoin::getUserId, activityJoin.getUserId()));
        for (ActivityJoin join : list) {
            Long id = join.getActivityId();
            Activity joinedActivity = activityService.getById(id);
            if (DateUtil.parseDate(activity.getTime()).isAfter(DateUtil.parseDate(joinedActivity.getTime()))) {
                throw new CustomException("-1", "您当前报名的活动与之前报名的活动【" + joinedActivity.getName() + "】有时间冲突");
            }
        }
        return Result.success(activityJoinService.save(activityJoin));
    }

    @PutMapping
    public Result<?> update(@RequestBody ActivityJoin activityJoin) {
        return Result.success(activityJoinService.updateById(activityJoin));
    }

    @DeleteMapping("/{id}")
    public Result<?> delete(@PathVariable Long id) {
        activityJoinService.removeById(id);
        return Result.success();
    }

    @GetMapping("/{id}")
    public Result<?> findById(@PathVariable Long id) {
        return Result.success(activityJoinService.getById(id));
    }

    @GetMapping
    public Result<?> findAll() {
        return Result.success(activityJoinService.list());
    }

}
